package cn.mldn.eshop.datalink.controller;

import cn.mldn.eshop.datalink.service.EshopProductService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class DataLinkController {
    @Resource
    private EshopProductService eshopProductService;
    @Resource(name = "myRedisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/product")
    public String getProduct(Long productId) {

        String dimJson = this.redisTemplate.opsForValue().get("dim_product_" + productId);

        if (dimJson == null || dimJson.equals("")) {
            String productDataJSON = this.eshopProductService.findProductById(productId);
            System.out.println(productDataJSON);
            if (productDataJSON != null && !"".equals(productDataJSON)) {
                JSONObject productDataJSONObject = JSONObject.parseObject(productDataJSON);
                String productPropertyjSON = this.eshopProductService.findProductPropertyById(productId);
                if (productPropertyjSON != null && !productPropertyjSON.equals("")) {
                    productDataJSONObject.put("product_property", JSONObject.parseObject(productPropertyjSON));
                }
                String productSpecificationJson = this.eshopProductService.findProductSpecificationById(productId);
                if (productSpecificationJson != null && !productSpecificationJson.equals("")) {
                    productDataJSONObject.put("product_specification", JSONObject.parseObject(productSpecificationJson));
                }
                this.redisTemplate.opsForValue().set("dim_product_" + productId, productDataJSONObject.toJSONString());

                return productDataJSONObject.toJSONString();


            }


        }
        return dimJson;
    }
}
